package com.pricy.me.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pricy.me.R;
import com.pricy.me.StreamProductsActivity;
import com.pricy.me.model.Product;
import com.pricy.me.model.TempData;
import com.pricy.me.model.User;

public class ReceiverData extends BroadcastReceiver {
    private String urlRoot;

	@Override
    public void onReceive(final Context context, Intent intent) {
		urlRoot = context.getString(R.string.lien);
    	final Timer mTimer = new Timer();
    	TimerTask mTimerTask = new TimerTask() {

    	    @Override
    	    public void run() {
    	    	
    	    	 ConnectivityManager conMgr = (ConnectivityManager)   context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	         if (conMgr.getActiveNetworkInfo() != null &&  conMgr.getActiveNetworkInfo().isAvailable() &&    conMgr.getActiveNetworkInfo().isConnected()) {
    	        	 // Log.e("CONNECTION PRICYME","Connected = " + mTimer.toString());
    	        	 TempData td = new TempData();
    	        	 List<TempData> list = td.getList(context);
    	        	 if(list.size() > 0) showNotification(context);
    	        	 
    	        	 for (final TempData t : list) {
							
				        	// Create a new HttpClient and Post Header
				            HttpClient httpclient = new DefaultHttpClient();
				            
				            // Execute HTTP Post Request
							try {
								User user = new User();
								user.loadData(context);
								String url = "";
								if(t.getType() == TempData.CURRENCY){
									url = urlRoot+"api/user/currency?id="+user.getId()+"&currency="+t.getData();
								}
								else if(t.getType() == TempData.CATEGORIE){
									url = urlRoot+"api/usercategory/?json="+URLEncoder.encode(t.getData(), "UTF-8")+"&user="+user.getId();
								}
								else if(t.getType() == TempData.PRODUCT){
									
									url = urlRoot+"api/product/new?json="+URLEncoder.encode(t.getUrl(), "UTF-8");
								}
								
								HttpPost httppost = new HttpPost(url);
								HttpResponse response = httpclient.execute(httppost);
								String reponse = EntityUtils.toString(response.getEntity());
								if(t.getType() == TempData.PRODUCT){
									String productJson = reponse;
					                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
					                Product p = (Product) gson.fromJson(productJson, Product.class);
					                Log.e("PHOTO", Environment.getExternalStorageDirectory().getPath()+"/product-"+t.getData()+".jpg");
					                Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/product-"+t.getData()+".jpg");
					                uploadPicture(""+p.getId(), bitmap);
					                // Save Product
					                Product product = new Product();
					                product.addProduct(context,p);
								}
								
								
								Log.e("REPONSE",reponse);
							} catch (UnknownHostException e) {
							} catch (HttpHostConnectException e) {
							} catch (ClientProtocolException e) {
							} catch (IOException e) {
							}
							
					}
    	        	td.clear(context);
						
					
    	         }
    	         else cancel();

    	     }
    	};
    	
        ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        if (cm == null)
            return;
        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
            // Send here
        	mTimer.scheduleAtFixedRate(mTimerTask,1000,5000);
        	
        } else {
            // Do nothing or notify user somehow
        	// Log.e("CONNECTION PRICYME","Not Connected = " + mTimer.toString());
        	
        }

    }
    
    private void showNotification(Context context) {
    	PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, StreamProductsActivity.class), 0);
    	
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.icon)
                .setContentTitle("Synchronisation")
                .setContentText("Synchronisation des données effectuée avec succés.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.getNotification());
        
    } 
    
    private void uploadPicture(String id, Bitmap picture) throws ClientProtocolException, IOException{
		HttpClient httpClient = new DefaultHttpClient();
		    HttpPost postRequest = new HttpPost(urlRoot+"api/product/upload?id="+id);
		    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		    try{
		        ByteArrayOutputStream bos = new ByteArrayOutputStream();
		        picture.compress(CompressFormat.JPEG, 100, bos);
		        byte[] data = bos.toByteArray();
		        ByteArrayBody bab = new ByteArrayBody(data, "product-"+id+".jpg");
		        reqEntity.addPart("file", bab);
		    }
		    catch(Exception e){
		        reqEntity.addPart("picture", new StringBody(""));
		    }
		    postRequest.setEntity(reqEntity);       
		    HttpResponse response = httpClient.execute(postRequest);
		    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
		    String sResponse;
		    StringBuilder s = new StringBuilder();
		    while ((sResponse = reader.readLine()) != null) {
		        s = s.append(sResponse);
		    }
		    Log.e("UPLOAD", s.toString());
	}
    
    
}